package com.zl.cms.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zl.basic.CommonUtil.JsonUtil;
import com.zl.cms.dto.AjaxObj;
import com.zl.cms.web.CmsSessionContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zl.basic.model.Captcha;
import com.zl.cms.model.Role;
import com.zl.cms.model.RoleType;
import com.zl.cms.model.User;
import com.zl.cms.service.IUserService;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * User: zl email:c3tc3tc3t@126.com Date: 14-3-1 Time: 下午9:18
 */
@Controller
public class LoginController {

  private IUserService userService;

  public IUserService getUserService() {
    return userService;
  }

  @Inject
  public void setUserService(IUserService userService) {
    this.userService = userService;
  }


  @RequestMapping(value = "/login", method = RequestMethod.GET)
  public String login() {
    return "admin/login";
  }

  @RequestMapping(value = "/login", method = RequestMethod.POST)
  public String login(String username, String password, String validateCode, Model model,
      HttpSession session) {
    String cc = (String) session.getAttribute("checkcode");
    if (!cc.equals(validateCode)) {
      model.addAttribute("error", "验证码不正确");
      return "admin/login";
    }

    User loginUser = userService.login(username, password);
    session.setAttribute("loginUser", loginUser);
    List<Role> rs = userService.listUserRoles(loginUser.getId());
    boolean isAdmin = isRole(rs, RoleType.ROLE_ADMIN);
    session.setAttribute("isAdmin", isAdmin);
    // System.out.println(getAllActions(rs, session));
    // 不是超级管理员才存储用户访问的类和方法
    if (!isAdmin) {
      session.setAttribute("allActions", getAllActions(rs, session));
      session.setAttribute("isAudit", isRole(rs, RoleType.ROLE_AUDIT));
      session.setAttribute("isPublish", isRole(rs, RoleType.ROLE_PUBLISH));
    }
    session.removeAttribute("checkcode");
	  CmsSessionContext.addSession(session);
	  System.out.println("存储了Session "+session.getId());
    return "redirect:/admin";
  }



  @SuppressWarnings("unchecked")
  private Set<String> getAllActions(List<Role> rs, HttpSession session) {
    Set<String> actions = new HashSet<>();
    Map<String, Set<String>> allAuths =
        (Map<String, Set<String>>) session.getServletContext().getAttribute("allAuths");
    actions.addAll(allAuths.get("base"));
    for (Role r : rs) {
      if (r.getRoleType() == RoleType.ROLE_ADMIN) continue;
      actions.addAll(allAuths.get(r.getRoleType().name()));
    }
    return actions;
  }



  private boolean isRole(List<Role> rs, RoleType rt) {
    for (Role r : rs) {
      if (r.getRoleType() == rt) return true;
    }
    return false;
  }



  @RequestMapping("/drawCheckCode")
  public void drawCheckCode(HttpServletResponse response, HttpSession session) {
    response.setContentType("image/jpg");

    int width = 180;
    int height = 28;

    Captcha c = Captcha.getInstance();
    c.set(width, height);
    String checkcode = c.generateCode();
    session.setAttribute("checkcode", checkcode);
    try {
      OutputStream os = response.getOutputStream();
      ImageIO.write(c.getnerateCheckImg(checkcode), "jpg", os);
    } catch (IOException e) {
      e.printStackTrace();
    }

  }

}
